<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">

        <!-- 输入框和按钮 -->
        <div class="el-row">
          <!-- 输入框 -->
          <div class="el-input-group">
            <el-input
              v-model.number="value"
              placeholder="请输入内容"
              clearable
            >
              <el-button slot="append" icon="el-icon-search" @click="queryUserList(value)" />
            </el-input>
          </div>
          <!-- 按钮 -->
          <el-button type="primary" @click="dialogFormVisible=true">添加用户</el-button>
        </div>

        <!-- 表格 -->
        <el-table
          border
          :data="tableData"
          stripe
          style="width: 100%"
        >
          <el-table-column
            label="#"
            type="index"
            width="50"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="280"
          />
          <el-table-column
            prop="email"
            label="邮箱"
            width="280"
          />
          <el-table-column
            prop="mobile"
            label="电话"
            width="280"
          />
          <el-table-column
            prop="role_name"
            label="角色"
            width="280"
          />
          <el-table-column
            label="状态"
            width="180"
          >
            <template slot-scope="{row}">
              <el-switch
                v-model="row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="modifyUserStatus(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{row}">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="editUser(row)" />
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUserSingle(row)" />
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="disRoles(row)" />
            </template>

          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          :current-page="queryData.pagenum"
          :page-sizes="[2, 5,10, 20]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 添加用户弹出层 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form ref="addFormList" :model="addFormList" :rules="addRoleRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFormList.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFormList.password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFormList.email" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addFormList.mobile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户的弹层 -->
    <el-dialog title="修改用户" :visible.sync="dialogFormEditVisible">
      <el-form ref="editFormList" :model="editFormList" :rules="editRoleRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editFormList.username" :disabled="true" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFormList.email" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editFormList.mobile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="onEditSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的弹层 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormDisVisible">
      <div>
        <p>当前的用户：{{ disNewRoles.username }}</p>
        <p>当前的角色：{{ disNewRoles.role_name }}</p>
        <div class="fenpeirole-box">
          <p>分配新角色：
          </p>
          <div class="fenpeirole">
            <el-select v-model="value" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :value="item.id"
                :label="item.roleName"
              />
            </el-select>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormDisVisible = false">取 消</el-button>
        <el-button type="primary" @click="onAssignSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleList } from '@/api/roles'
import {
  assignUserRoles,
  editUserSubmit,
  getDataList,
  addUser,
  editUserStatus,
  deleteUser } from '@/api/user.js'
export default {
  name: 'UserList',
  data() {
    return {
      value: '',
      // 分页
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 总数
      total: 0,
      // 状态
      status: false,
      // 用户id
      userId: 0,
      // 表格数据
      tableData: [],
      // 显示弹层
      dialogFormVisible: false,
      // 添加的内容
      addFormList: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改的数据
      editFormList: {},
      // 修改数据的规则
      editRoleRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2-20个长度之间', trigger: 'blur' },
          { pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '请输入正确邮箱号码', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '请输入正确手机号', trigger: 'blur' }
        ]
      },
      // 添加的规则
      addRoleRules: {
        username: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在2-10个长度之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在2-10个长度之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2-20个长度之间', trigger: 'blur' },
          { pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '请输入正确邮箱号码', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '请输入正确手机号', trigger: 'blur' }
        ]
      },
      // 用户id
      currentData: {
        uId: '',
        type: ''
      },
      // 编辑用户的弹层
      dialogFormEditVisible: false,
      // 分配角色的弹层
      dialogFormDisVisible: false,
      // 分配新角色
      disNewRoles: {},
      // 选项
      options: []
    }
  },

  created() {
    this.getUserList()
  },

  methods: {
    // 获取用户数据列表
    async getUserList() {
      const res = await getDataList(this.queryData)
      // console.log(res)
      this.tableData = res.users
      this.total = res.total
      this.status = res.users.mg_state
      this.uId = res.users.id
    },

    // 查询用户信息
    async queryUserList(input) {
      this.queryData.query = input
      try {
        const res = await getDataList(this.queryData)
        this.tableData = res.users
        this.getUserList()
      } catch (err) {
        console.log(err)
      }
    },
    // 添加用户
    async onSave() {
      try {
        this.$refs.addFormList.validate()
        const res = await addUser(this.addFormList)
        console.log(res)
        this.getUserList()
        this.$message.success('添加成功')
        this.dialogFormVisible = false
        this.addFormList = {
          username: '',
          password: '',
          email: '',
          mobile: '' }
      } catch (err) {
        console.log(err)
      }
    },

    // 修改用户状态
    async  modifyUserStatus(row) {
      try {
        console.log(row)
        this.currentData.uId = row.id
        this.currentData.type = row.mg_state
        // console.log(this.currentData)
        await editUserStatus(this.currentData)
        this.$message.success('修改成功')
      } catch (err) {
        console.log(err)
      }
    },
    // 编辑用户提交
    editUser(row) {
      // console.log(row)
      this.dialogFormEditVisible = true
      this.editFormList = row
    },
    // 编辑提交
    async  onEditSave() {
      try {
        this.$refs.editFormList.validate()
        await editUserSubmit(this.editFormList)
        this.getUserList()
        this.$message.success('修改成功')
        this.dialogFormEditVisible = false
      } catch (err) {
        console.log(err)
      }
    },
    // 删除单个用户
    async deleteUserSingle(row) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteUser(row.id)
        this.getDataList()
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    // 分配角色
    async disRoles(row) {
      try {
        this.dialogFormDisVisible = true
        // 获取选择的列表
        this.disNewRoles.username = row.username
        this.disNewRoles.role_name = row.role_name
        this.disNewRoles.id = row.id
        this.disNewRoles.rid = this.value
        // console.log(this.disNewRoles.rid)
        const res = await roleList()
        this.options = res
      } catch (err) {
        console.log(err)
      }
    },
    async  onAssignSave() {
      try {
        await assignUserRoles(this.disNewRoles.id, this.disNewRoles.rid)
        this.$message.success('分配成功了哟')
        this.dialogFormDisVisible = false
      } catch (err) {
        console.log(err)
      }
    },
    // 每页多少条
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 当前页多少条
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryData.pagenum = val
      this.getUserList()
    }
  }
}
</script>

<style scoped lang='scss'>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

 .el-row{
    display: flex;
    .el-input {
     min-width: 475px;
     max-width: 520px;

    }
  }
   ::v-deep .el-input-group{
       width: 0;
     }

     .el-button--primary{
       margin-left: 20px;
     }
.el-card{
 padding: 0 20px;
}
  .el-table{
    margin: 15px 0;
  }
.fenpeirole-box{
  display: flex;
  .fenpeirole{
    flex: 1;
  }
}

</style>
